package com.beiji.lib.pen.ui.renderer

import android.graphics.*
import android.util.Log
import com.beiji.lib.pen.model.DotUnit
import com.beiji.lib.pen.model.PenStroke
import com.tqltech.tqlpencomm.bean.Dot

/**
 * Path渲染器
 * Created by X on 2018/6/21.
 */
class MarkPathRenderer {

    private val path = Path()

    private var startX: Float = 0f
    private var startY: Float = 0f
    private var endX: Float = -1f
    private var endY: Float = -1f
    private val clear = Paint()

    private var preX: Float = 0f
    private var preY: Float = 0f
    private var lastX: Float = -1f
    private var lastY: Float = -1f

    init {
        clear.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
    }

    fun reset() {
        startX = -1f
        startY = -1f
        endX = 0f
        endY = 0f
        preX = 0f
        preY = 0f
        lastX = -1f
        lastY = -1f
    }

    fun reset(bitmapCanvas: Canvas, markBitmap: Bitmap, markCanvas: Canvas){
        reset()
        bitmapCanvas.drawBitmap(markBitmap, 0f, 0f, null)
        markCanvas.drawPaint(clear)
    }

    fun draw(canvas: Canvas, stroke: PenStroke, dotMatrix: Matrix, paint: Paint?) {

        val path = Path()
        for (i in stroke.list.indices) {
            val point = stroke.list[i]
            if (i == 0) {
                path.moveTo(point.x.toFloat(), point.y.toFloat())
            } else {
                val lastPoint = stroke.list[i - 1]
                path.quadTo(lastPoint.x.toFloat(), lastPoint.y.toFloat(), (lastPoint.x + point.x) / 2f, (lastPoint.y + point.y) / 2f)
            }
        }
        path.transform(dotMatrix)
        paint!!.alpha = 63
        canvas.drawPath(path, paint)
    }

    fun draw(bitmapCanvas: Canvas, dot: DotUnit, paint: Paint?, markBitmap: Bitmap, markCanvas: Canvas) {
        val curX = dot.x.toFloat()
        val curY = dot.y.toFloat()
        if (dot.type == Dot.DotType.PEN_DOWN || preX == 0f) {
            path.reset()
            path.moveTo(curX, curY)
        } else {
            path.quadTo(preX, preY, (preX + curX) / 2, (preY + curY) / 2)
            lastX = (preX + curX) / 2
            lastY = (preY + curY) / 2
        }
        preX = curX
        preY = curY
        markCanvas.drawPaint(clear)
        markCanvas.drawPath(path, paint!!)
//        bitmapCanvas.drawPath(path,paint)
        if (dot.type == Dot.DotType.PEN_UP) {
            bitmapCanvas.drawBitmap(markBitmap, 0f, 0f, null)
            markCanvas.drawPaint(clear)
            //有时候会丢失pen_down事件，所以在up的时候重置一下preX，下一次强制走pen_down
            reset()
        }
    }

}